
angular.module("ApiServiceMod", ["GraphqlServiceMod", "BmobServiceMod"])
    .service('apiService', ['$q', '$http', "myConfig", 'graphqlService', "bmobService", function($q, $http, myConfig, graphqlService, bmobService) {
        this.getList = function(obj, query, variables) {
            var dataFromType = obj === 'note' ? 2 : myConfig.dataFromType;  //this is for test note list
            switch(dataFromType) {
                case 1:
                    return bmobService.getRecords(query);
                    break;
                case 2:
                    return graphqlService.query(query, variables);
                    break;
                default:
                    var res = [{"id":1}];
                    switch(obj) {
                        case 'site':
                            res = myConfig.isOtherNav ? others_site_list : site_list;
                            break;
                        default:
                            break;
                    }
                    var defer = $q.defer();
                    defer.resolve(res);
                    return defer.promise
                    break;
            }
        };
        
        this.parseXHS = function(share_txt, opusIndexs) {
            var defer = $q.defer();

            // 使用正则表达式匹配链接
            // share_txt = "57 过客发布了一篇小红书笔记，快来看吧！ 😆 vb20hhsvC2z4908 😆 http://xhslink.com/B/B4Fwcy，复制本条信息，打开【小红书】App查看精彩内容！"
            const urlPattern = /https?:\/\/[\w.\/-]+/;
            const match = share_txt.match(urlPattern);

            if (match && match != null) {
                const url = match[0];                
                $http({
                    method: 'POST',
                    url: "/xhsapi/xhs/",
                    //url: "http://127.0.0.1:8000/xhs/",
                    data: {
                        "url": url,
                        "download": true,
                        "index": opusIndexs, //["1"]
                        "skip": false
                    },
                    timeout: 2*60*1000
                }).then(function (response) {
                    defer.resolve(response.data);
                }).catch(err => {
                    defer.reject(`请求解析失败${err.message ?? ""}`);
                });
            } else {
                defer.reject("输入的分享中没有找到作品链接地址");
            }
            
            return defer.promise;
        };

        this.getRecentFiles = function(opusTime) {
            var defer = $q.defer();
             
            $http({
                method: 'GET',
                url: "/xhsapi/recent_files?days=1&contains=" + opusTime,
                timeout: 1*60*1000
            }).then(function (response) {
                defer.resolve(response.data);
            }).catch(err => {
                defer.reject("请求最近文件失败");
            });
            
            return defer.promise;
        };
    }]);